package cn.com.hhrcw.message;

import cn.hutool.core.util.StrUtil;
import com.dtflys.forest.config.ForestConfiguration;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.http.NameValueRequestBody;
import com.dtflys.forest.interceptor.Interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author lixingxing
 */
@Component
@Slf4j
public class MessageInterceptor implements Interceptor<Object> {

    @Autowired
    private ForestConfiguration forestConfiguration;

    @Override
    public boolean beforeExecute(ForestRequest request) {
        long time = System.currentTimeMillis();

        String appid = (String) forestConfiguration.getVariableValue("appId");
        request.addHeader("x-api-key", appid);
        request.addHeader("If-None-Match",time);
        request.addHeader("mode","increment");
        if (StrUtil.equalsIgnoreCase(request.getContentType(), MediaType.MULTIPART_FORM_DATA_VALUE)) {
            List<NameValueRequestBody> body = request.getBody();
            for (NameValueRequestBody forestRequestBody : body) {
                if (forestRequestBody.getValue().getClass().isArray()) {
                    forestRequestBody.setValue(StrUtil.join(",", forestRequestBody.getValue()));
                }
            }
        }
        return true;
    }

    @Override
    public void onError(ForestRuntimeException e, ForestRequest forestRequest, ForestResponse forestResponse) {
        log.error("请求失败");
    }

    @Override
    public void onSuccess(Object o, ForestRequest forestRequest, ForestResponse forestResponse) {
        log.error("请求成功");
    }
}
